"""
文件管理模型
"""
from django.db import models
from django.conf import settings
import os


class FileCategory(models.Model):
    """文件分类"""
    
    name = models.CharField(max_length=100, unique=True, verbose_name='分类名称')
    description = models.TextField(blank=True, null=True, verbose_name='分类描述')
    allowed_extensions = models.CharField(max_length=200, blank=True, null=True, verbose_name='允许的文件扩展名')
    max_file_size = models.PositiveIntegerField(default=10485760, verbose_name='最大文件大小(字节)')  # 10MB
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'file_management_category'
        verbose_name = '文件分类'
        verbose_name_plural = '文件分类'
        ordering = ['name']
        
    def __str__(self):
        return self.name


class UploadedFile(models.Model):
    """上传文件"""
    
    FILE_TYPES = [
        ('image', '图片'),
        ('document', '文档'),
        ('video', '视频'),
        ('audio', '音频'),
        ('archive', '压缩包'),
        ('other', '其他'),
    ]
    
    uploader = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='上传者')
    category = models.ForeignKey(FileCategory, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='文件分类')
    
    original_name = models.CharField(max_length=255, verbose_name='原始文件名')
    file = models.FileField(upload_to='uploads/%Y/%m/%d/', verbose_name='文件')
    file_type = models.CharField(max_length=20, choices=FILE_TYPES, verbose_name='文件类型')
    file_size = models.PositiveIntegerField(verbose_name='文件大小(字节)')
    mime_type = models.CharField(max_length=100, verbose_name='MIME类型')
    
    # 文件信息
    description = models.TextField(blank=True, null=True, verbose_name='文件描述')
    tags = models.CharField(max_length=200, blank=True, null=True, verbose_name='标签')
    
    # 访问控制
    is_public = models.BooleanField(default=False, verbose_name='是否公开')
    allowed_users = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        blank=True,
        related_name='accessible_files',
        verbose_name='允许访问的用户'
    )
    
    # 统计信息
    download_count = models.PositiveIntegerField(default=0, verbose_name='下载次数')
    view_count = models.PositiveIntegerField(default=0, verbose_name='查看次数')
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'file_management_uploaded_file'
        verbose_name = '上传文件'
        verbose_name_plural = '上传文件'
        ordering = ['-created_at']
        
    def __str__(self):
        return self.original_name
    
    @property
    def file_extension(self):
        """文件扩展名"""
        return os.path.splitext(self.original_name)[1].lower()
    
    @property
    def file_size_mb(self):
        """文件大小(MB)"""
        return round(self.file_size / 1024 / 1024, 2)
    
    def can_access(self, user):
        """检查用户是否可以访问文件"""
        if self.is_public:
            return True
        if self.uploader == user:
            return True
        if user.is_admin:
            return True
        return self.allowed_users.filter(id=user.id).exists()


class FileAccessLog(models.Model):
    """文件访问日志"""
    
    ACTION_CHOICES = [
        ('view', '查看'),
        ('download', '下载'),
        ('upload', '上传'),
        ('delete', '删除'),
    ]
    
    file = models.ForeignKey(UploadedFile, on_delete=models.CASCADE, verbose_name='文件')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
    action = models.CharField(max_length=20, choices=ACTION_CHOICES, verbose_name='操作类型')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(verbose_name='用户代理')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='操作时间')
    
    class Meta:
        db_table = 'file_management_access_log'
        verbose_name = '文件访问日志'
        verbose_name_plural = '文件访问日志'
        ordering = ['-created_at']
        
    def __str__(self):
        return f"{self.user.username} {self.get_action_display()} {self.file.original_name}"


class FileShare(models.Model):
    """文件分享"""
    
    file = models.ForeignKey(UploadedFile, on_delete=models.CASCADE, verbose_name='分享文件')
    shared_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='分享人')
    share_token = models.CharField(max_length=64, unique=True, verbose_name='分享令牌')
    
    # 分享设置
    password = models.CharField(max_length=20, blank=True, null=True, verbose_name='访问密码')
    expires_at = models.DateTimeField(blank=True, null=True, verbose_name='过期时间')
    max_downloads = models.PositiveIntegerField(blank=True, null=True, verbose_name='最大下载次数')
    
    # 统计信息
    access_count = models.PositiveIntegerField(default=0, verbose_name='访问次数')
    download_count = models.PositiveIntegerField(default=0, verbose_name='下载次数')
    
    is_active = models.BooleanField(default=True, verbose_name='是否有效')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'file_management_share'
        verbose_name = '文件分享'
        verbose_name_plural = '文件分享'
        ordering = ['-created_at']
        
    def __str__(self):
        return f"分享 {self.file.original_name}"
    
    def is_expired(self):
        """检查是否已过期"""
        if self.expires_at:
            from django.utils import timezone
            return timezone.now() > self.expires_at
        return False
    
    def is_download_limit_reached(self):
        """检查是否达到下载限制"""
        if self.max_downloads:
            return self.download_count >= self.max_downloads
        return False
